<?php

class Application_Model_Mail_Sender
{

    protected $_zm;
    protected $_tpl;
    protected $_to;
    protected $_tokens;

    public function __construct()
    {
        $this->_zm = new Zend_Mail('utf8');
    }

    public function selectTemplate($code)
    {
        $tpl    = new Application_Model_MailTemplate();
        $mapper = new Application_Model_MailTemplateMapper();
        $tpl    = $mapper->findByCode($code, $tpl);

        if ($tpl->getId() > 0 && $tpl->getContent())
        {
            $this->_tpl = $tpl;
        }
    }

    public function hasTemplate()
    {
        return !empty($this->_tpl);
    }

    public function setTo($email)
    {
        $this->_to = $email;
    }

    public function setTokens($tokens)
    {
        if (is_array($tokens))
        {
            $this->_tokens = $tokens;
        }
    }

    public function send()
    {

        $mail_html    = $this->_tokenize($this->_tpl->getContent());
        $mail_subject = $this->_tokenize($this->_tpl->getSubject());

        $this->_zm->setBodyHtml($mail_html);
        $this->_zm->setFrom($this->_tpl->getFromEmail(), $this->_tpl->getFromName());
        $this->_zm->addTo($this->_to);
        $this->_zm->setSubject($mail_subject);
        return $this->_zm->send();
    }

    private function _tokenize($value)
    {
        if (is_array($this->_tokens))
        {
            foreach ($this->_tokens as $tkn_key => $tkn_value)
            {
                if (is_scalar($tkn_value))
                {
                    $value = str_replace('{' . $tkn_key . '}', $tkn_value, $value);
                }
            }
        }
        return $value;
    }
}